package main_task

import (
	"go_server/game_server/api/service/bag"
	"go_server/game_server/constants"
	"go_server/game_server/dao/task_info_dao"
	"go_server/game_server/dataconfig/config_manager"
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/game_server/world_manager"
	"go_server/zinx/ziface"
	"go_server/zinx/zlog"
	"go_server/zinx/znet"
	"gorm.io/datatypes"
)

type GetMainTaskPrizeApi struct {
	znet.BaseRouter
}

// 领取任务奖励
func (*GetMainTaskPrizeApi) Handle(request ziface.IRequest) {
	msg := &pb.GetMainTaskPrizeC2S{}
	if !util.PBParseRet(request, msg) {
		return
	}

	conn := request.GetConnection()
	roleId := ServiceObj.GetRoleId(request)

	if msg.TaskId <= 0 {
		world_manager.WorldMgrObj.SendClientErrMsg(roleId, request, pb.ErrorCodeManager_PARAM_ERROR, nil)
	}

	// 获取当前用户主线任务进度
	fields := []string{"chapter", "main_task"}
	row := task_info_dao.GetTaskInfoByRoleId(roleId, fields)

	var chapter int32                     // 当前正在进行的章节
	taskDetail := make(map[int32][]int32) // 任务进度

	if row != nil {
		chapter = row.Chapter

		if row.MainTask.Data() != nil {
			taskDetail = row.MainTask.Data()
		}
	}

	if chapter <= 0 {
		chapter = 1
	}

	taskProgress, ok := taskDetail[msg.TaskId]
	if !ok || taskProgress[2] != 1 {
		zlog.Errorf("任务未达成或者已领取奖励")
		world_manager.WorldMgrObj.SendClientErrMsg(roleId, request, pb.ErrorCodeManager_TASK_UNCOMPLETE, nil)
		return
	}

	taskConfig, ok := config_manager.GetStcTableTask_SheetTaskById(msg.TaskId)
	if !ok || taskConfig.Chapter != chapter {
		zlog.Errorf("任务配置不存在或不能提前领取后续章节任务奖励")
		world_manager.WorldMgrObj.SendClientErrMsg(roleId, request, pb.ErrorCodeManager_MAIN_TASK_CANT_GOT_PRIZE, nil)
		return
	}

	taskDetail[msg.TaskId][2] = 2

	prizeMap := make(map[int32]int32)

	if taskConfig.Condition != constants.MAIN_TASK_CHAPTER_EVENT_TYPE {
		chapterTaskInfo := config_manager.GetStcTableTask_SheetTaskInfoByChapter(constants.MAIN_TASK, constants.MAIN_TASK_CHAPTER_EVENT_TYPE, chapter)
		chapterTaskId := chapterTaskInfo.Id
		preRequisites := chapterTaskInfo.PrereQuisites
		limitProcess := int32(len(preRequisites))

		var process int32

		chapterInfo, ok := taskDetail[chapterTaskId]
		if ok {
			process = chapterInfo[1] + 1
		} else {
			process = 1
		}

		if process >= limitProcess {
			taskDetail[chapterTaskId] = []int32{chapterTaskId, limitProcess, 1}
		} else {
			taskDetail[chapterTaskId] = []int32{chapterTaskId, process, 0}
		}

		for _, v := range taskConfig.TaskReward {
			prizeMap[v.Value[0]] = v.Value[1]
		}
	} else {
		chapter++
		for _, v := range taskConfig.ChapterReward {
			prizeMap[v.Value[0]] = v.Value[1]
		}
	}

	res := &pb.GetMainTaskPrizeS2C{
		TaskId: msg.TaskId,
		State:  taskDetail[msg.TaskId][2],
	}

	// 先推送客户端消息
	conn.SendBuffPBMsg(uint32(pb.ProtocolManager_GetMainTaskPrize), res)

	// 最后操作数据库
	upTaskInfo := task_info_dao.TaskInfo{
		RoleId:   roleId,
		Chapter:  chapter,
		MainTask: datatypes.NewJSONType(taskDetail),
	}

	task_info_dao.UpdateTaskInfo(&upTaskInfo, fields) // 修改任务状态

	msgS2C := ServiceObj.GetMainTaskChapterInfo.GetMainTaskChapterInfoS2c(roleId)
	conn.SendBuffPBMsg(uint32(pb.ProtocolManager_GetMainTaskChapterInfo), msgS2C)

	bag.AddItemBatch(roleId, prizeMap) // 发送奖励
}
